<template>
  <div class="box">
    <var-sticky :offset-top="0" class="top">
      <var-app-bar title="新闻" title-position="center" />
      <var-tabs elevation v-model:active="active">
        <var-tab v-for="it in types" @click="selectType(it.typeId)">
          {{ it.typeName }}
        </var-tab>
      </var-tabs>
    </var-sticky>
    <div class="body" ref="body">
      <div v-for="i in lists" class="item">
        <div class="title" @click="goDetail(i.newsId)">{{ i.title }}</div>
        <div class="detail">{{ i.digest }}</div>
        <div v-for="img in i.imgList">
          <var-image
            ripple
            lazy
            :src="img"
            :loading="loading"
            :error="loading"
            @click="preview(img)"
          />
        </div>
        <div class="detail">{{ i.postTime }}</div>
        <div class="detail">{{ i.source }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getNewsType, getNewsList } from '@/api/news'
import { onMounted, onUnmounted, watch } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
import { ref } from 'vue'
import _ from 'lodash'
import { useRouter, useRoute } from 'vue-router'
import { ImagePreview } from '@varlet/ui'
import loading from '@/assets/images/loading3.gif'
const $router = useRouter()
const $route = useRoute()

const active = ref(0)
const types: any = ref([])
const lists: any = ref([])
const body: any = ref(null)
let page: any = ref(1)
let typeId = ref(0)
const top = ref(0)
const obj = {
  app_id: 'yjroqmhvmjywnnqk',
  app_secret: 'Mck5hX919x1Wx6dJExAaF13u5zc8SYmR',
}
const getType = async () => {
  const res = await getNewsType(obj)
  types.value = res.data
  setTimeout(() => {
    selectType(types.value[0].typeId)
  }, 1000)
}

const selectType = async (id: any = false) => {
  if (id) {
    typeId.value = id
    page.value = 1
    lists.value = []
  }
  const obj1 = {
    ...obj,
    typeId: typeId.value,
    page: page.value,
  }
  const res = await getNewsList(obj1)
  lists.value = [...lists.value, ...res.data]
}

const goDetail = (item: any) => {
  $router.push({
    path: '/newsDetail',
    query: {
      id: item,
    },
  })
}

// 滚动事件处理函数
const handleScroll = _.throttle(() => {
  if (body.value) {
    const containerHeight = body.value.scrollHeight
    const scrollTop = body.value.scrollTop
    const clientHeight = body.value.clientHeight
    // 计算滚动条距离底部的距离
    const scrollDistanceFromBottom =
      containerHeight - (scrollTop + clientHeight)
    if (scrollDistanceFromBottom <= 50) {
      page.value++
      selectType()
    }
  }
}, 1000)

const preview = (src: string) => {
  ImagePreview({
    images: [src],
    closeable: true,
  })
}

onMounted(() => {
  getType()
  if (body.value) {
    body.value.addEventListener('scroll', handleScroll)
  }
  watch(
    () => $route,
    (to, from) => {
      if (from && from.path == '/news') body.value.scrollTop = top.value
    },
    { immediate: true, deep: true }, // 立即执行一次且深度监听
  )
})

// 在组件卸载时移除事件监听器
onUnmounted(() => {
  if (body.value) {
    body.value.removeEventListener('scroll', handleScroll)
  }
})

onBeforeRouteLeave(() => {
  top.value = body.value.scrollTop
})
</script>

<script lang="ts">
export default {
  name: 'news',
}
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  flex-direction: column;
  height: 100%;

  .body {
    flex: 1;
    overflow-y: auto;
    padding: 10px;

    .item {
      margin: 10px 0;
      box-shadow: 0 0 10px #ccc;
      padding: 10px;
      border-radius: 10px;
      box-sizing: border-box;
      position: relative;

      .title {
        font-size: 18px;
        text-align: center;
        padding: 0 50px;
        box-sizing: border-box;
      }

      .detail {
        font-size: 14px;
        color: #6e6e6e;
        text-indent: 2em;
      }

      .img {
        width: 100%;
      }
    }
  }
}
</style>
